package com.bawei.library_common.mvvm

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.databinding.DataBindingUtil
import androidx.databinding.ViewDataBinding
import androidx.fragment.app.Fragment
import com.bawei.library_base.loadsir.EmptyCallback
import com.bawei.library_base.loadsir.ErrorCallback
import com.bawei.library_base.loadsir.LottieLoadingCallback
import com.blankj.utilcode.util.ToastUtils
import com.kingja.loadsir.callback.Callback.OnReloadListener
import com.kingja.loadsir.core.LoadService
import com.kingja.loadsir.core.LoadSir


abstract class BaseFragment<VDB: ViewDataBinding> : Fragment(),IBaseView {

    protected lateinit var viewDataBinding:VDB

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?,
    ): View? {
        viewDataBinding = DataBindingUtil.inflate(inflater,getLayout(),container,false)
        initData()
        initListener()

        return viewDataBinding.root
    }

    abstract fun getLayout():Int //返回布局id
    abstract fun initData() //初始化数据
    abstract fun initListener()//事件监听

    private lateinit var  mLoadService: LoadService<*>
    private var isShowedContent = false

    override fun showContent() {
        if (null != mLoadService) {
            isShowedContent = true
            mLoadService.showSuccess()
        }
    }

    override fun showLoading() {
        if (null != mLoadService) {
            mLoadService.showCallback(LottieLoadingCallback::class.java)
        }
    }

    override fun showEmpty() {
        if (null != mLoadService) {
            mLoadService.showCallback(EmptyCallback::class.java)
        }
    }

    override fun showFailure(message: String?) {
        if (null != mLoadService) {
            if (!isShowedContent) {
                mLoadService.showCallback(ErrorCallback::class.java)
            } else {
                ToastUtils.showShort(message)
            }
        }
    }

     fun setLoadSir(view: View?) {
        mLoadService = LoadSir.getDefault()
            .register(view,
                OnReloadListener {
                        v: View? -> onRetryBtnClick()
                })
    }

    /**
     * 失败重试,加载事件
     */
    open fun onRetryBtnClick(){}


}